import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '@/router/index'
import { loginAPI,loginByFaceApi } from '@/apis/loginApi'
import { ElMessage } from 'element-plus'


export const useUserStore = defineStore('user', () => {
  // 定义管理用户数据的state
  const userInfo = ref({
    name:'',
    token:''
  })

  // 从本地存储中加载数据
  const loadUserInfoFromLocalStorage = () => {
    const savedUserInfo = JSON.parse(localStorage.getItem('userInfo'))
    if (savedUserInfo) {
      console.log('用户信息本地存在！')
      userInfo.value = savedUserInfo
      return
    }
    localStorage.removeItem('userInfo')
    sessionStorage.clear()
    if(router.currentRoute.value.path==='/login'){
      return
    }
    ElMessage({ type: 'error', message: '登录状态丢失，请重新登录！' })
    router.replace('/login')
  }

  // 在 store 创建时加载数据
  loadUserInfoFromLocalStorage()

  //账密登录
  const getUserInfo = async ({ account, password }) => {
    console.log('本地没有用户信息，开始请求接口')
    const res = await loginAPI({ phone: account, password: password })
    if(res.code===0){
      userInfo.value = res.data
      // 保存数据到本地存储
    localStorage.setItem('userInfo', JSON.stringify(res.data))
    }
    return res
  }
  //人脸登录
  const getUserInfoByFace = async (face) => {
    console.log('本地没有用户信息，开始请求接口')
    const res = await loginByFaceApi(face)
    if(res.code===0){
      userInfo.value = res.data
      // 保存数据到本地存储
    localStorage.setItem('userInfo', JSON.stringify(res.data))
    }
    return res
  }




  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = {}
    localStorage.removeItem('userInfo')
  }

  // 返回state和actions
  return {
    userInfo,
    getUserInfo,
    getUserInfoByFace,
    clearUserInfo
  }
})